package com.zhaoxi.project.sys.service;

import com.zhaoxi.common.utils.DateUtils;
import com.zhaoxi.common.utils.StringUtils;
import com.zhaoxi.common.utils.file.FileUploadUtils;
import com.zhaoxi.common.utils.file.FileUtils;
import com.zhaoxi.framework.config.ServerConfig;
import com.zhaoxi.framework.config.ZhaoXiConfig;
import com.zhaoxi.framework.web.BaseService;
import com.zhaoxi.framework.web.PageData;
import com.zhaoxi.project.sys.domain.SysAttachment;
import com.zhaoxi.project.sys.mapper.AttachmentMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.LinkOption;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;

/**
 * 附件Service业务层处理
 *
 * @author zhaoxi
 * @date 2023-11-09
 */
@Service
public class AttachmentService extends BaseService {
  @Autowired
  private AttachmentMapper attachmentMapper;

  @Autowired
  private ServerConfig serverConfig;

  //查询数据集合
  public List<PageData> getList(PageData pd) {
    return attachmentMapper.getList(pd);
  }

  //查询数据对象 通过id
  public PageData getById(PageData pd) {
    PageData pd1 = new PageData();
    if (pd.getLong("id") == null) {
      return null;
    }
    pd1.put("id", pd.get("id"));
    List<PageData> list = attachmentMapper.getList(pd1);
    if (list.size() > 0) {
      return list.get(0);
    }
    return null;
  }

  //查询数据对象 是否有重复的，可设置id，同一个id并不是重复。
  public int checkUserUnique(PageData pd) {
    String userId = pd.getString("id");
    pd.put("id", null);
    List<PageData> list = attachmentMapper.getList(pd);
    int i = 0;
    for (PageData k : list) {
      if (!k.getString("id").equals(userId)) {
        i++;
      }
    }
    return i;
  }


  //新增
  public PageData add(PageData pd) {
    return this.responses(attachmentMapper.add(pd));
  }

  //更新
  public PageData edit(PageData pd) {
    return this.responses(attachmentMapper.edit(pd));
  }

  //删除
  public PageData del(PageData pd) throws IOException {
    String url = (String) this.getById(pd).get("url");
    this.delFile(url);
    return this.responses(attachmentMapper.del(pd));
  }

  /**
   * 新增多个附件
   *
   * @param pd 附件集合
   * @return 结果
   */

  public PageData moreAdd(PageData pd ) {
    List<PageData> attachmentList = pd.getListPd("list");
    List<Long> ids = new ArrayList<Long>();
    for (PageData attachment : attachmentList) {
      attachment.put("createTime",DateUtils.getNowDate());
      attachment.put("createBy",this.getUsername());
      attachment.put("tenantId",this.getTenantId());
      attachmentMapper.add(attachment);
      ids.add(attachment.getLong("id"));
    }
    PageData res = PageData.success();
    res.put("ids", StringUtils.join(ids, ","));
    return res;
  }
//
//  /**
//   * 上传图片
//   * @param fileList 文件数组
//   */
//  public PageData uploadPicture(List<MultipartFile> fileList) throws IOException {
//    PageData pd = this.getPageData();
//    pd.put("type","img");
//    return this.uploadAttachment(fileList,pd);
//  }
  /**
   * 上传附件信息
   * @param fileList 文件数组
   */
  public PageData uploadAttachment(List<MultipartFile> fileList) throws IOException {
    // 上传文件路径
    String filePath = ZhaoXiConfig.getPicturePath();
    List<String> urls = new ArrayList<String>();
    List<String> fileNames = new ArrayList<String>();
    List<String> newFileNames = new ArrayList<String>();
    for (MultipartFile file : fileList) {
      // 上传并返回新文件名称.
      String name = file.getName();
      String fileName = FileUploadUtils.upload(filePath, file);
      String url = serverConfig.getUrl() + fileName;
      urls.add(url);
      fileNames.add(fileName);
      newFileNames.add(FileUtils.getName(fileName));
    }
    PageData res = PageData.success();
    res.put("urls", StringUtils.join(urls, ","));
    res.put("fileNames", StringUtils.join(fileNames, ","));
    res.put("newFileNames", StringUtils.join(newFileNames, ","));
    return res;
  }

  /**
   * 删除附件信息
   *
   * @param url 附件路径
   * @return 结果
   */

  public void delByUrl(String url) throws IOException {
    this.delFile(url);
    attachmentMapper.delByUrl(url);
  }
public void delFile(String url) throws IOException {
  String filePath = ZhaoXiConfig.getPicturePath() + StringUtils.substringAfter(url, "picture");
  Path path = Paths.get(filePath);
  if(Files.exists(path)){
      Files.delete(path);
  }
}

}
